package com.anli.xianliu2;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Collections;

/**
 * @author: LI-CI-GAO
 * 作者: licigao
 * 日期: 2021/8/29  21:28
 * 描述:
 */
@Aspect
@Component
public class XianLiuAop2 {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private DefaultRedisScript<Long> redisScript=new DefaultRedisScript<>();

    @Pointcut("execution(public * com.anli.web.*.*(..))")
    public void pointcut(){};


    @Around("pointcut() && @annotation(com.anli.xianliu2.Xianliu2)")
    public Object process(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

        Xianliu2 annotation = signature.getMethod().getAnnotation(Xianliu2.class);
        int value = annotation.value();

        //String lur="if redis.call('incr',KEYS[1]) <= tonumber(ARGV[1]) then return 1 else return 0 end";
        String lur="if redis.call('incr',KEYS[1]) <= tonumber(ARGV[1]) then if redis.call('get',KEYS[1]) == '1' then redis.call('expire',KEYS[1],ARGV[2]) end return 1 else return 0 end";

        redisScript.setScriptText(lur);
        redisScript.setResultType(Long.class);

        Long xianliu = redisTemplate.execute(redisScript, Collections.singletonList("xianliu"), value,10);

        if(xianliu==1){
           return proceedingJoinPoint.proceed();
        }else{
            HttpServletResponse response = requestAttributes.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print("负载过大");
            writer.close();
            writer=null;
            return null;
        }

    }

}
